package com.candy.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//        将ServletRequest、ServletResponse转换成HttpServletRequest、HttpServletResponse
        HttpServletRequest req=(HttpServletRequest)request;
        HttpServletResponse resp=(HttpServletResponse)response;
//        获取HttpSession对象
        HttpSession session=req.getSession();
//        当session不为空且可以从session获取用户的信息不为空的情况下，表示用户为登录状态
        boolean logined=(session!=null) && (session.getAttribute("user")!=null);
//        获取用户的请求路径
        String requestUrl=req.getRequestURI();
//        当用户已经登录 且 是访问index.jsp 且 访问的资源为login的时候 不需要拦截，其
//        其他的情况则需要用户重新访问登录界面进行登录操作
        if(!logined && !requestUrl.endsWith("index.jsp") && !requestUrl.endsWith("login") ){
//            需要让用户重新登录处理
            resp.sendRedirect(req.getContextPath()+"/index.jsp");
            return;
        }
        chain.doFilter(request, response);



    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("登录拦截过滤器的初始化方法");
    }

    @Override
    public void destroy() {
        System.out.println("登录拦截过滤器的销毁方法");
    }
}
